package com.mrli.cat.weather.activity;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.mrli.cat.weather.R;
import com.mrli.cat.weather.database.WeatherContract;
import com.mrli.cat.weather.model.City;

import java.util.List;

public class CityAdapter extends CursorAdapter implements SectionIndexer{
    private SectionIndexer mIndexer;    //字母表分组

    @Override
    public Object[] getSections() {
        return mIndexer.getSections();
    }

    @Override
    public int getPositionForSection(int sectionIndex) {
        return mIndexer.getPositionForSection(sectionIndex);
    }

    @Override
    public int getSectionForPosition(int position) {
        return mIndexer.getSectionForPosition(position);
    }

    //绑定到视图的视图对象
    public static class ViewHolder {
        public final TextView sort_key_view;
        public final TextView city_name_view;

        public ViewHolder(View view) {
            this.sort_key_view = (TextView) view.findViewById(R.id.sort_key);
            this.city_name_view = (TextView) view.findViewById(R.id.city_name);
        }
    }

    public CityAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
    }

    public void setmIndexer(SectionIndexer mIndexer) {
        this.mIndexer = mIndexer;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.city_item, null);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setTag(viewHolder);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        //判断是否要显示小节
        int section = mIndexer.getSectionForPosition(cursor.getPosition());
        if (cursor.getPosition() == mIndexer.getPositionForSection(section)) {
            String sortKey = cursor.getString(cursor.getColumnIndex(WeatherContract.CityEntry.COLUMN_SORT));
            viewHolder.sort_key_view.setText(sortKey);
            LinearLayout keyLayout = (LinearLayout) view.findViewById(R.id.sort_key_layout);
            keyLayout.setVisibility(View.VISIBLE);
        } else {
            //如果不是小节, 设置小节视图为不可见
            LinearLayout keyLayout = (LinearLayout) view.findViewById(R.id.sort_key_layout);
            keyLayout.setVisibility(View.GONE);
        }
        String cityName = cursor.getString(cursor.getColumnIndex(WeatherContract.CityEntry.COLUMN_NAME));
        viewHolder.city_name_view.setText(cityName);
    }
}
